package com.richapp.launcher.serialport.gateway.command;


import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.gpio.GPIOServer;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.message.MsgConstant;
import com.richapp.launcher.net.mobile.message.DeviceAddReply;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.serialport.gateway.ControlInstructionMessage;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.launcher.serialport.gateway.GatewayServer;
import com.richapp.net.util.HexTool;
import com.richapp.net.util.StringUtil;

public class AddCmd extends BasicCommand {

	private int index = 0;
	private String[] instructions = new String[8];
	private static AddCmd addCmd = null;
	
	private AddCmd() {
		
	}
	
	public static AddCmd getInstance(){
		if(addCmd == null){
			addCmd = new AddCmd();
		}
		return addCmd;
	}

	// 查询设备
	public void query(String cpuBoxId,String deviceId, String deviceNumber,String way) {
		this.ID = deviceId;
		this.Number = deviceNumber;
		this.Query = "35";
        this.Way = way;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationCMD());
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_QUERY);
		GatewayServer.getInstance().writeMessage(cim);
	}

	// 添加单个设备
	public void addOneDevice() {
		ControlInstructionMessage cim = new ControlInstructionMessage(null,null,null,null);
		cim.setHexInstruction(GatewaytConstant.INSTRUCTION_ADD_ONE_STR);
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_ADD_ONE);
		GatewayServer.getInstance().writeMessage(cim);
	}

	// 盲添命令
	public void blindAdd() {
		GPIOServer.getInstance().mindAddStartBeep();
		instructions = new String[8];
		ControlInstructionMessage cim = new ControlInstructionMessage(null,null,null,null);
		cim.setHexInstruction(GatewaytConstant.INSTRUCTION_ADD_ALL_STR);
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_ADD_ALL);
		GatewayServer.getInstance().writeMessage(cim);
	}
	
	/**
	 * 解析反馈的数据
	 */
	private void addDevices() {
		DeviceModelDao dmd = new DeviceModelDao(GatewayServer.getInstance().getContext());
		DeviceModel deviceModel = null;
		BoxModel bm = new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox();

		String cpuNumber = bm.getBoxCpuId().substring(bm.getBoxCpuId().length()-4, bm.getBoxCpuId().length()-1);

		String deviceId = null;
		int deviceCountH = 0;
		int deviceCountL = 0;
		int deviceCount = 0;
		int databaseDeviceCount = 0;

		int index = 0;
		for(String in : instructions){
			if(index == 0){

			}else{
				if(in != null){
					in = in.substring(6, 36);
					String[] result = StringUtil.getSplitResult6(in);

					for(String resultStr : result){
						//获取类型
						deviceId = resultStr.substring(0,2);
						//获取类型个数
						deviceCountH = HexTool.HexToInt(resultStr.substring(2, 4));
						deviceCountL = HexTool.HexToInt(resultStr.substring(4, 6));
						deviceCount = ((deviceCountH<<8) & 0xFF00) | (deviceCountL & 0xFF);

						//根据类型确定路数
						int wayCount = 1;
						if("1B".equals(deviceId) || "1F".equals(deviceId)){
							wayCount = 2;
						}else if("1C".equals(deviceId)){
							wayCount = 3;
						}else if("1D".equals(deviceId)){
							wayCount = 4;
						}


						if("01".equals(deviceId)){
							databaseDeviceCount = dmd.getDeviceListByBoxCpuIdDeviceId(bm.getBoxCpuId(), deviceId,"00").size();
						}else {
							databaseDeviceCount = dmd.getDeviceListByBoxCpuIdDeviceId(bm.getBoxCpuId(), deviceId,GatewaytConstant.getNumberString(wayCount,2) ).size();
						}
						if(deviceCount > databaseDeviceCount){
							int lastNumber = 0x01;
							if(GatewaytConstant.ID_TYPE_CARBON_DIOXIDE_STR.equals(deviceId) || GatewaytConstant.ID_TYPE_HAND_HELD_STR.equals(deviceId)){
								lastNumber = 0x0001;
							}

							Object[] objs = null;
							int addCount = deviceCount-databaseDeviceCount;
							for(int i = 0 ; i < addCount ; i++){
								//获取number
								if ("01".equals(deviceId)){
									objs = getMultiDeviceNumber(bm.getBoxCpuId(),deviceId,lastNumber,"00");
								}else {
									objs = getMultiDeviceNumber(bm.getBoxCpuId(),deviceId,lastNumber,"01");
								}

								lastNumber = Integer.parseInt(objs[0].toString());

								for(int j = 0; j< wayCount; j++){
									//添加数据
									String wayNumber = GatewaytConstant.getNumberString((j+1),2);
									deviceModel = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId,objs[1].toString(),wayNumber);
									if(deviceModel == null){
										deviceModel = new DeviceModel();
										deviceModel.setBoxCpuId(bm.getBoxCpuId());
										deviceModel.setDeviceId(deviceId);
										if("01".equals(deviceId)){
											wayNumber="00";
										}
										deviceModel.setWay(wayNumber);
										deviceModel.setDeviceNumber(objs[1].toString());
										String	deviceNumber;
										if(objs[1].toString().length()==2){
											deviceNumber=objs[1].toString()+"号";
										}else {
											deviceNumber = objs[1].toString().substring(2) + "号";
										}
										//二路
										if(2 == wayCount && 1 == j){
											deviceModel.setDeviceName(cpuNumber+""+ GatewaytConstant.getDeviceName(deviceId) + "" + deviceNumber+ (j+2)+"路");
										}else{
											deviceModel.setDeviceName(cpuNumber+""+ GatewaytConstant.getDeviceName(deviceId)+ "" + deviceNumber + (j+1)+"路");
										}
										if ("17".equals(deviceId)){
											deviceModel.setDeviceStatus("CC");
										} else {
											deviceModel.setDeviceStatus("00");
										}
										deviceModel.setOnlineStatus("BD");
										deviceModel.setSignal("3F");
										Log.d(getClass().getName(),"要添加的设备信息:"+deviceModel);
										dmd.add(deviceModel);
									}else{
										//存在则数据不动
									}
								}
							}
						}else{
							//无需添加
						}
					}
				}
			}
			index++;
		}
	}
	/*
	  private void addDevices() {
		DeviceModelDao dmd = new DeviceModelDao(GatewayServer.getInstance().getContext());
		DeviceModel deviceModel = null;
		BoxModel bm = new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox();

		String cpuNumber = bm.getBoxCpuId().substring(bm.getBoxCpuId().length()-4, bm.getBoxCpuId().length()-2);

		String deviceId = null;
		int deviceCountH = 0;
		int deviceCountL = 0;
		int deviceCount = 0;
		int databaseDeviceCount = 0;

		int index = 0;
		for(String in : instructions){
			if(index == 0){

			}else{
				if(in != null){
					in = in.substring(6, 36);
					String[] result = StringUtil.getSplitResult6(in);

					for(String resultStr : result){
                        //获取类型
						deviceId = resultStr.substring(0,2);
                        //获取类型个数
						deviceCountH = HexTool.HexToInt(resultStr.substring(2, 4));
						deviceCountL = HexTool.HexToInt(resultStr.substring(4, 6));
						deviceCount = ((deviceCountH<<8) & 0xFF00) | (deviceCountL & 0xFF);

                        if("1A".equals(deviceId) || "1B".equals(deviceId) || "1C".equals(deviceId) || "1D".equals(deviceId)
                                || "1E".equals(deviceId) || "1F".equals(deviceId)){
                            //根据类型确定路数
                            int wayCount = 1;
                            if("1B".equals(deviceId) || "1F".equals(deviceId)){
                                wayCount = 2;
                            }else if("1C".equals(deviceId)){
                                wayCount = 3;
                            }else if("1D".equals(deviceId)){
                                wayCount = 4;
                            }

                            databaseDeviceCount = dmd.getDeviceListByBoxCpuIdDeviceId(bm.getBoxCpuId(), deviceId,GatewaytConstant.getNumberString(wayCount,2) ).size();
                            if(deviceCount > databaseDeviceCount){
                                int lastNumber = 0x0001;
                                Object[] objs = null;
                                int addCount = deviceCount-databaseDeviceCount;
                                for(int i = 0 ; i < addCount ; i++){
                                    //获取number
                                    objs = getMultiDeviceNumber(bm.getBoxCpuId(),deviceId,lastNumber,"01");
                                    lastNumber = Integer.parseInt(objs[0].toString());

                                    for(int j = 0; j< wayCount; j++){
                                        //添加数据
                                        String wayNumber = GatewaytConstant.getNumberString((j+1),2);
                                        deviceModel = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId,objs[1].toString(),wayNumber);
                                        if(deviceModel == null){
                                            deviceModel = new DeviceModel();
                                            deviceModel.setBoxCpuId(bm.getBoxCpuId());
                                            deviceModel.setDeviceId(deviceId);
                                            deviceModel.setWay(wayNumber);
                                            deviceModel.setDeviceNumber(objs[1].toString());
                                            //deviceModel.setDeviceName(GatewaytConstant.getDeviceName(deviceId)+cpuNumber+objs[1].toString().substring(1));
											//二路
											if(2 == wayCount && 1 == j){
												deviceModel.setDeviceName(cpuNumber+"|"+ GatewaytConstant.getDeviceName(deviceId) + "|" + (j+2)+"路");
											}else{
												deviceModel.setDeviceName(cpuNumber+"|"+ GatewaytConstant.getDeviceName(deviceId) + "|" + (j+1)+"路");
											}
                                            deviceModel.setDeviceStatus("FF");
                                            deviceModel.setOnlineStatus("BD");
                                            deviceModel.setSignal("3F");
                                            dmd.add(deviceModel);
                                        }else{
                                            //存在则数据不动
                                        }
                                    }
                                }
                            }else{
                                //无需添加
                            }
                        }else{
                            databaseDeviceCount = dmd.getDeviceListByBoxCpuIdDeviceId(bm.getBoxCpuId(), deviceId,"01").size();
                            if(deviceCount > databaseDeviceCount){
                                int lastNumber = 0x0001;
                                Object[] objs = null;
                                int addCount = deviceCount-databaseDeviceCount;
                                for(int i = 0 ; i < addCount ; i++){
                                    //获取number
                                    objs = getDeviceNumber(bm.getBoxCpuId(),deviceId,lastNumber,"01");
                                    lastNumber = Integer.parseInt(objs[0].toString());

                                    //添加数据
                                    deviceModel = dmd.getByCpuIdDeviceIdDeviceNumber(bm.getBoxCpuId(),deviceId,objs[1].toString(),"01");
                                    if(deviceModel == null){
                                        deviceModel = new DeviceModel();
                                        deviceModel.setBoxCpuId(bm.getBoxCpuId());
                                        deviceModel.setDeviceId(deviceId);
                                        deviceModel.setDeviceNumber(objs[1].toString());
                                        deviceModel.setWay("01");
                                        //deviceModel.setDeviceName(GatewaytConstant.getDeviceName(deviceId)+cpuNumber+objs[1].toString().substring(1));
                                        deviceModel.setDeviceName(cpuNumber+"|"+ GatewaytConstant.getDeviceName(deviceId) + "|" + lastNumber);
                                        deviceModel.setDeviceStatus("FF");
                                        deviceModel.setOnlineStatus("BD");
                                        deviceModel.setSignal("3F");
                                        dmd.add(deviceModel);
                                    }else{
                                        //存在则数据不动
                                    }
                                }
                            }else{
                                //无需添加
                            }
                        }
					}
				}
			}
			index++;
		}
	}*/
	
	private Object[] getDeviceNumber(String boxCpuId,String deviceId ,int lastNumber,String way){
		Object[] objs = new Object[2];
		
		int number = lastNumber;
		String deviceNumber = null;
		DeviceModelDao dmd = new DeviceModelDao(GatewayServer.getInstance().getContext());
		DeviceModel dm = null;
		while(true){
			deviceNumber = GatewaytConstant.getNumberString(number, 4);
			dm = dmd.getByCpuIdDeviceIdDeviceNumber(boxCpuId,deviceId, deviceNumber,way);
			if(dm == null){
				break;
			}
			number++;
		}
		
		objs[0] = number;
		objs[1] = deviceNumber;
		return objs;
	}

    private Object[] getMultiDeviceNumber(String boxCpuId,String deviceId ,int lastNumber,String way){
        Object[] objs = new Object[2];

        int number = lastNumber;
        String deviceNumber = null;
        DeviceModelDao dmd = new DeviceModelDao(GatewayServer.getInstance().getContext());
        DeviceModel dm = null;
        while(true){
			if(GatewaytConstant.ID_TYPE_CARBON_DIOXIDE_STR.equals(deviceId)
					|| GatewaytConstant.ID_TYPE_HAND_HELD_STR.equals(deviceId)){
				deviceNumber = GatewaytConstant.getNumberString(number, 4);
			}else{
				deviceNumber = GatewaytConstant.getNumberString(number, 2);
			}
            dm = dmd.getByCpuIdDeviceIdDeviceNumber(boxCpuId,deviceId, deviceNumber,way);
            if(dm == null){
                break;
            }
            number++;
        }

        objs[0] = number;
        objs[1] = deviceNumber;
        return objs;
    }

	@Override
	public void analyticalCmd(String upStreamCmd) {
		if(index < 8){
			instructions[index++] = upStreamCmd;
		}
		
		if(index == 8){

			GatewayServer.setLastMessage(null);

			index = 0;
			addDevices();
			instructions = new String[8];

			//解析完成，通知蜂鸣器动作
			GPIOServer.getInstance().mindAddStopBeep();

			//反馈添加结果
			DeviceModelDao dmd = new DeviceModelDao(GatewayServer.getInstance().getContext());
			BoxModel currentBox = new BoxModelDao(GatewayServer.getInstance().getContext()).getCurrentBox();
			DeviceAddReply dar = new DeviceAddReply();
			dar.setUserName(currentBox.getUserName());
			dar.setCurrentBoxCpuId(currentBox.getBoxCpuId());
			
			dar.setDeviceList(dmd.getDeviceList());

			JSONObject jsonObject = (JSONObject)JSON.toJSON(dar);

			//发送所有当前手机
			UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());

			if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
				jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
				//发送服务器
				RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
				//发送其他机顶盒
				BoxServer.getInstance().sendAllBoxMessage(jsonObject.toJSONString());
			}
		}
		
	}
}
